<template>
  <el-dialog :model-value="showAddVideoGroupDialog" :title="props.editInfo.id ? '编辑课程分组' : '新建课程分组'" width="30%"
    @close="resetForm" :close-on-click-modal="false">
    <div style="height: 65vh;overflow-y: auto;padding-right: 20px;">
      <el-form ref="ruleFormRef" :model="form" :rules="rules" label-width="auto">
        <el-form-item label="课程分组名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入课程分组名称" />
        </el-form-item>

        <el-form-item label="副标题" prop="subhead">
          <el-input type="textarea" v-model="form.subhead" placeholder="请输入课程副标题" />
        </el-form-item>

        <el-form-item label="课程标签" prop="label">
          <el-input v-model="form.label" placeholder="多个标签请用逗号分隔" />
        </el-form-item>

        <el-form-item label="车型" prop="carIds">
          <el-select v-model="form.carIds" multiple placeholder="请选择" style="width: 100%" :disabled="isEdit">
            <el-option v-for="item in carList" :key="item.value" :label="`${item.label}(${item.tag})`"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="课程封面（横图）">
          <el-input v-model="form.img" style="display: none"></el-input>
          <div class="avatar-uploader" @click="openImageDialog('img')">
            <el-image v-if="form.img" :src="form.img" class="avatar" fit="contain"></el-image>
            <i v-else class="el-icon-plus avatar-uploader-icon"><el-icon>
                <Plus />
              </el-icon></i>
            <div v-if="form.img" class="mask">替换</div>
            <el-icon v-if="form.img" class="del-image" :size="20" @click.stop="handleDelImg('img')">
              <CircleCloseFilled />
            </el-icon>
          </div>
        </el-form-item>

        <el-form-item label="课程封面（竖图）">
          <el-input v-model="form.imgTwo" style="display: none"></el-input>
          <div class="avatar-uploader" @click="openImageDialog('imgTwo')">
            <el-image v-if="form.imgTwo" :src="form.imgTwo" class="avatar" fit="contain"></el-image>
            <i v-else class="el-icon-plus avatar-uploader-icon"><el-icon>
                <Plus />
              </el-icon></i>
            <div v-if="form.imgTwo" class="mask">替换</div>
            <el-icon v-if="form.imgTwo" class="del-image" :size="20" @click.stop="handleDelImg('imgTwo')">
              <CircleCloseFilled />
            </el-icon>
          </div>
        </el-form-item>

        <el-form-item label="课程详情">
          <ArtWangEditor v-model="form.remark" />
        </el-form-item>
      </el-form>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" :loading="editLoading" @click="submitForm(ruleFormRef)">确认</el-button>
        <el-button @click="resetForm">取消</el-button>
      </div>
    </template>
  </el-dialog>
  <image-selected-dialog v-if="showImageChooseDialog" :single-type="selectImageSingle"
    :show-image-choose-dialog="showImageChooseDialog" @close-dialog="handleCloseImageDialog"
    :operationType="false"></image-selected-dialog>
</template>

<script setup lang="ts">
import { operationCategory } from '@/api/questionbanklabel'
import { Plus } from '@element-plus/icons-vue'
import { reactive, ref } from 'vue'
import { useUserStore } from '@/store/modules/user'

import { ElMessage, FormInstance, FormRules } from 'element-plus'
import { getcarmodellist } from '@/api/questionbank'
import ImageSelectedDialog from '@/views/decoration/diyComponents/ImageSelectedDialog.vue'

const userStore = useUserStore()

const props = defineProps({
  showAddVideoGroupDialog: {
    type: Boolean
  },
  editInfo: {
    type: Object,
    default: () => {
      return {
        id: ''
      }
    }
  }
})

const isEdit = computed(() => {
  return props.editInfo.children && props.editInfo.children.length > 0
})

const ruleFormRef = ref<FormInstance>()

interface Form {
  name: string
  img: string
  imgTwo: string
  parentId: number
  carIds: any
  subhead: string
  label: string
  pageUrlType: string
  remark: string
}

const form = reactive({
  name: '',
  img: '',
  imgTwo: '',
  pageUrlType: '',
  label: '',
  subhead: '',
  carIds: [],
  parentId: 0,
  remark: ''
})

const rules = reactive<FormRules<Form>>({
  name: [{ required: true, message: '不能为空', trigger: 'blur' }],
  img: [{ required: true, message: '不能为空', trigger: 'blur' }],
  carIds: [{ required: true, message: '不能为空', trigger: 'change', type: 'array' }],
  // subhead: [{ required: true, message: '不能为空', trigger: 'blur' }],
  remark: [{ required: true, message: '不能为空', trigger: 'blur' }],
  pageUrlType: [{ required: true, message: '不能为空', trigger: 'blur' }]
})

const editLoading = ref(false)

interface carLists {
  label: string
  value: string
  tag: string
}
const carList = ref<Array<carLists>>([])

const emit = defineEmits(['closeDialog'])

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid) => {
    if (valid) {
      if (props.editInfo.id) {
        handleEdit()
      } else {
        handleAdd()
      }
    } else {
    }
  })
}

async function handleAdd() {
  try {
    editLoading.value = true
    const res = await operationCategory.newAddCategory({
      ...form,
      carIds: form.carIds.join(',')
    })
    if (res.code === '00000') {
      emit('closeDialog', true)
      ElMessage.success('新增成功')
    }
  } catch (e) {
  } finally {
    editLoading.value = false
  }
}

async function handleEdit() {
  try {
    editLoading.value = true
    const res = await operationCategory.eidtCategory(
      {
        ...form,
        carIds: form.carIds.join(',')
      },
      props.editInfo.id
    )
    if (res.code === '00000') {
      emit('closeDialog', true)
      ElMessage.success('编辑成功')
    }
  } catch (e) {
  } finally {
    editLoading.value = false
  }
}

//上传限制大小格式等
const beforeAvatarUpload = (file: any) => {
  const isLt2M = file.size / 10240 / 10240 < 2
  if (file.type != 'image/jpeg' && file.type != 'image/png' && file.type != 'image/gif') {
    ElMessage.error('图片类型仅支持JPG/PNG/GIF格式!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('上传头像图片大小不能超过 20MB!!')
    return false
  }
}

const resetForm = () => {
  emit('closeDialog')
}

//车型下拉接口
const getcarmodellistinfo = async () => {
  let obj = {}
  const res = await getcarmodellist.getcarmodelId(obj)
  if (res.code == 0) {
    carList.value = res.data
  }
}

const showImageChooseDialog = ref(false)
const selectImageSingle = ref(true)

const currentImageType = ref('img') // 'img' 或 'imgTwo'
const openImageDialog = (type: string) => {
  currentImageType.value = type
  showImageChooseDialog.value = true
}

const handleCloseImageDialog = (value: any) => {
  if (value && value.fileUrl) {
    if (currentImageType.value === 'img') {
      form.img = value.fileUrl
    } else if (currentImageType.value === 'imgTwo') {
      form.imgTwo = value.fileUrl
    }
  }
  showImageChooseDialog.value = false
}
const handleDelImg = (e: string) => {
  if (e === 'img') {
    form.img = ''
  } else {
    form.imgTwo = ''
  }
}


onMounted(() => {
  if (props.editInfo.id) {
    form.name = props.editInfo.name
    form.img = props.editInfo.img
    form.imgTwo = props.editInfo.imgTwo
    form.carIds = props.editInfo.carIds.split(',')
    form.subhead = props.editInfo.subhead
    form.label = props.editInfo.label
    form.remark = props.editInfo.remark
  }
  form.pageUrlType = props.editInfo.pageUrlType
  form.parentId = props.editInfo.parentId

  getcarmodellistinfo()
})
</script>

<style scoped lang="scss">
.avatar-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 180px;
  height: 180px;
  line-height: 180px;
  text-align: center;

  .mask {
    position: absolute;
    bottom: 0;
    left: 0;
    width: 100%;
    height: 24px;
    background-color: rgba(0, 0, 0, 0.6);
    display: flex;
    align-items: center;
    justify-content: center;
    opacity: 0;
    transition: opacity 0.3s ease;
    color: #fff;
    font-size: 12px;
  }

  .del-image {
    display: none;
    position: absolute;
    top: 0;
    right: 0;
    cursor: pointer;
    color: #8c939d;
  }

  &:hover .mask {
    opacity: 1;
  }

  &:hover .del-image {
    display: block;
  }
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 180px;
  height: 180px;
  line-height: 180px;
  text-align: center;
}

.avatar {
  width: 180px;
  height: 180px;
  display: block;
}
</style>
